package com.skivingcloud.report.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.skivingcloud.report.dto.DataSetTransformDto;
import com.skivingcloud.report.service.TransformStrategy;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class DictTransformServiceImpl implements TransformStrategy {
    private static final Logger log = LoggerFactory.getLogger(DictTransformServiceImpl.class);
    /**
     * 数据清洗转换 类型
     *
     * @return 类型-数据字典
     */
    @Override
    public String type() {
        return "dict";
    }

    /***
     * 清洗转换算法接口
     * @param def 数据集定义
     * @param data 数据
     * @return 转换后结果
     */
    @Override
    public List<Map<String, Object>> transform(DataSetTransformDto def, List<Map<String, Object>> data) throws JsonProcessingException {
        String transformScript = def.getTransformScript();
        if (StringUtils.isBlank(transformScript)) {
            return data;
        }
        JsonNode jsonObject = new ObjectMapper().readTree(transformScript);

        data.forEach(dataDetail -> dataDetail.forEach((key, value) -> {
            if (jsonObject.has(key)) {
                String string = jsonObject.get(key).findValue(value.toString()).asText();
                if (StringUtils.isNotBlank(string)) {
                    dataDetail.put(key, string);
                }
            }
        }));
        return data;
    }
}
